import api from "./api.js";

function formatTime(time) {
	if (typeof time !== "number" || time < 0) {
		return time;
	}

	var hour = parseInt(time / 3600);
	time = time % 3600;
	var minute = parseInt(time / 60);
	time = time % 60;
	var second = time;

	return [hour, minute, second]
		.map(function(n) {
			n = n.toString();
			return n[1] ? n : "0" + n;
		})
		.join(":");
}

function formatDateTime(date, fmt = "yyyy-MM-dd hh:mm:ss") {
	if (!date) {
		return "";
	}
	if (typeof date === "number") {
		date = new Date(date * 1000);
	}
	var o = {
		"M+": date.getMonth() + 1, //月份
		"d+": date.getDate(), //日
		"h+": date.getHours(), //小时
		"m+": date.getMinutes(), //分
		"s+": date.getSeconds(), //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		S: date.getMilliseconds(), //毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(
			RegExp.$1,
			(date.getFullYear() + "").substr(4 - RegExp.$1.length)
		);
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(
				RegExp.$1,
				RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
			);
	return fmt;
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === "string" && typeof latitude === "string") {
		longitude = parseFloat(longitude);
		latitude = parseFloat(latitude);
	}

	longitude = longitude.toFixed(2);
	latitude = latitude.toFixed(2);

	return {
		longitude: longitude.toString().split("."),
		latitude: latitude.toString().split("."),
	};
}

var dateUtils = {
	UNITS: {
		年: 31557600000,
		月: 2629800000,
		天: 86400000,
		小时: 3600000,
		分钟: 60000,
		秒: 1000,
	},
	humanize: function(milliseconds) {
		var humanize = "";
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + "前";
				break;
			}
		}
		return humanize || "刚刚";
	},
	format: function(dateStr) {
		var date = this.parse(dateStr);
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS["天"]) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return number < 10 ? "0" + number : number;
		};
		return (
			date.getFullYear() +
			"/" +
			_format(date.getMonth() + 1) +
			"/" +
			_format(date.getDate()) +
			"-" +
			_format(date.getHours()) +
			":" +
			_format(date.getMinutes())
		);
	},
	parse: function(str) {
		//将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	},
};

const hexToRgba = (hex, opacity) => { //16进制颜色转rgba
	return "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," + parseInt(
		"0x" +
		hex.slice(5, 7)) + "," + opacity + ")"
}

const pay = (orderId, payment_code = uni.getSystemInfoSync().hostName === "alipay" ? 'alipay' : "wechatpay", classId,
	params = {}) => {
	return new Promise((resolve, reject) => {
		api.OrderPay({
			classId: classId || '',
			ids: orderId,
			// payment_code: 'wechatpay'
			payment_code,
			payment_type: 17,
			params,
			type: uni.getSystemInfoSync().hostName === "alipay" ? 1 : 2
		}).then(async (res) => {
			resolve(res)
			if (payment_code === "wechatpay" || payment_code === 'alipay') { // 判断是否微信支付
				const params = res.data.respData
				// 判断使用原生支付还是半屏
				if (res.data.money <= 0) {
					uni.redirectTo({
						url: '/pages/pay/pay_success/index?orderId=' +
							orderId
					})
					return
				}

				if (res.otherData === 1) {
					// 原生
					await uni.requestPayment({
						// #ifdef MP-ALIPAY
						provider: 'alipay',
						orderInfo: params.source,
						// #endif

						// #ifdef MP-WEIXIN
						provider: 'wxpay',
						timeStamp: params.payTimeStamp,
						nonceStr: params.paynonceStr,
						package: params.payPackage,
						signType: params.paySignType,
						paySign: params.paySign,
						// #endif
						success(res) {
							console.log(res, 'success');
							// #ifdef MP-WEIXIN
							uni.redirectTo({
								url: '/pages/pay/pay_success/index?orderId=' +
									orderId
							})
							// #endif

							// #ifdef MP-ALIPAY
							if (res.resultCode == 9000 && res.result) {
								uni.redirectTo({
									url: '/pages/pay/pay_success/index?orderId=' +
										orderId
								})
							} else {
								uni.showToast({
									title: '支付失败',
									icon: 'error'
								})
								uni.switchTab({
									url: '/pages/tab_bar/order/order'
								})
							}
							// #endif

						},
						fail(err) {
							if (classId) {
								uni.switchTab({
									url: '/pages/tab_bar/order/order'
								})
							}
						}
					})
				} else if (res.otherData === 2) {
					// 天厥收银台支付
					uni.openEmbeddedMiniProgram({ // 跳转其他小程序
						appId: params.appId, // appid
						path: params.path, // 跳转到小程序的路径
						// envVersion:develop, // 开发版
						success(result) {
							// 打开成功
							console.log('跳转支付')
						},
						fail() {
							console.log('跳转失败')
							if (classId) {
								uni.switchTab({
									url: '/pages/tab_bar/order/order'
								})
							}
						}
					})
				} else {
					// 其他
				}
			} else {
				if (res.data.status === 1) {
					uni.showToast({
						title: '支付成功',
						icon: "data.status",
						mask: true,
						success() {}
					})

					// setTimeout(()=>{
					// 	uni.switchTab({
					// 		url: '/pages/tab_bar/order/order' 
					// 		// url: '/pages/tab_bar/index'
					// 	})
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/pay/pay_success/index?orderId=' +
								orderId
							// url: '/pages/tab_bar/index'
						})
					}, 1000)
				}
			}
		}).catch(err => {
			reject("错误:" + JSON.stringify(err));
		})
	})
}

// 充值支付
const refillPay = (
	ids,
	params,
	payment_code = uni.getSystemInfoSync().hostName === 'alipay' ? 'alipay' : "wechatpay",
	payment_type = 201
) => {
	return new Promise((resolve, reject) => {
		api
			.OrderPay({
				ids,
				// payment_code: 'wechatpay'
				payment_code,
				payment_type: payment_type,
				params,
			})
			.then(async (res) => {
				resolve(res);
				const params = res.data.respData;
				if (res.otherData === 1) {
					// 原生
					await uni.requestPayment({
						provider: uni.getSystemInfoSync().hostName === 'alipay' ? 'alipay' :
							'wxpay',
						// #ifdef MP-ALIPAY
						orderInfo: params.source,
						// #endif

						// #ifdef MP-WEIXIN
						timeStamp: params.payTimeStamp,
						nonceStr: params.paynonceStr,
						package: params.payPackage,
						signType: params.paySignType,
						paySign: params.paySign,
						// #endif
						success(res) {
							// #ifdef MP-ALIPAY
							if (res.resultCode == 9000 && res.result) {
								uni.showToast({
									title: '支付成功',
								})
							} else {
								uni.showToast({
									title: '支付失败',
									icon: 'error'
								})
							}
							// #endif
						},
						fail(err) {
							console.log(err, 'err');
						}
					})
				} else if (res.otherData === 2) {
					// 天厥收银台支付
					uni.openEmbeddedMiniProgram({
						// 跳转其他小程序
						appId: params.appId, // appid
						path: params.path, // 跳转到小程序的路径
						success(result) {
							// 打开成功
							console.log("跳转支付");
						},
					});
				} else {}

			})
			.catch((err) => {
				reject("错误:" + JSON.stringify(err));
			});
	});
};

// 获取平台信息
const getSystemInfo = () => {
	return uni.getSystemInfoSync()
}


module.exports = {
	formatTime,
	formatDateTime,
	formatLocation,
	dateUtils,
	hexToRgba,
	pay,
	refillPay,
	getSystemInfo
};